package experiment.networkmodel;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.ArrayList;

public class NetworkServer implements Runnable, Updatable {

	protected final int SERVER_PORT;
	protected final int NUM_OF_CLIENTS;
	protected ServerSocket socket;
	protected ArrayList<SocketSpeaker> clients;
	protected Object toUpdate;

	public NetworkServer(int port, int maxClients){
		NUM_OF_CLIENTS = maxClients;
		SERVER_PORT = port;
		try {
			socket = new ServerSocket(SERVER_PORT, 0, InetAddress.getLocalHost());
		} catch (IOException e) {
			socket = null;
			System.err.println("Could not listen on port: " + SERVER_PORT);
			e.printStackTrace();
			System.exit(-1);
		}

	}
	
	public NetworkServer(int port) {
		NUM_OF_CLIENTS = 6;
		SERVER_PORT = port;
		try {
			socket = new ServerSocket(SERVER_PORT, 0, InetAddress.getLocalHost());
		} catch (IOException e) {
			socket = null;
			System.err.println("Could not listen on port: " + SERVER_PORT);
			e.printStackTrace();
			System.exit(-1);
		}
	}

	@Override
	public void run() {

		System.out.println("Network thread created");
		System.out.println(socket);
		listen();

	}

	@Override
	public void update(Object obj) {
		
		String temp = (String)obj;
		System.out.println(temp);
		
		for (int i = 0; i < clients.size(); i++) {
			clients.get(i).update(toUpdate);
		}
	}
	
	private void listen(){
		for (int i = 0; i < NUM_OF_CLIENTS; i++) {
			Thread t;
			SocketSpeaker client;
			try {
				client = new SocketSpeaker(socket.accept(), this);
			} catch (IOException e) {
				System.err.println("Client could not be connected");
				e.printStackTrace();
				client = null;
			}
			t = new Thread(client);
			t.setDaemon(true);
			t.start();
		}	
	}

	@Override
	public void kill(int status) {
		System.err.println("Program exiting with status: " + status);
		System.exit(status);
	}

}
